<template>
  <div>

    <vCommonPage :title="qrcodeType==='ali'?'请扫描支付宝支付码':'请使扫描微信支付码'">
      <div slot="customContent">
      <el-dialog :title="qrcodeType==='ali'?'请打开手机支付宝付款码，在右下方扫描，并在1分钟之内完成支付':'请打开手机微信付款码，在右下方扫描，并在1分钟之内完成支付'" 
      width="80%" 
      :visible.sync="showWaitingModal"
      :before-close="handleClose">
      <el-row style="padding:0" :gutter="20">
        <el-col :span="12">
          <el-card :body-style="{ padding: '0px' }">
            <img style="width:100%;display:block;" :src="readingUrl" class="image" />
          </el-card>
        </el-col>
          <span style="font-size:28px">姓名：{{this.$store.state.user.userinfo.name}}</span>
          <br>
          <br>
          <span style="font-size:30px;color:red;">支付金额：{{this.amount}}元</span>
          <br>
          <br>
        <el-col :span="12" style="display:flex;align-items:center;">
          <el-input ref="autofocus" v-model="barCode" autocomplete="off" @input="resetCountDown" @keyup.enter.native="checkinfo">
            <template slot="prepend">支付码:</template>
          </el-input>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer"></div>
        <el-button @click="cancelPay" class="cancel-btn" type="danger">取消支付</el-button>
    </el-dialog>
        
        <!-- start:自定义页面内容 -->
        <!-- <div class="page-wrap">
          <div class="item-wrap">
            <div class="phone-bg" :style="{backgroundImage: 'url('+ phoneBgUrl +')'}">
              <canvas id="qrcode" class="qrcode"></canvas>
              <div class="pay-info">
                <p>姓名:{{this.$store.state.user.userinfo.name}}</p>
                <p>金额：15.00元</p>
              </div>
            </div>
            <el-button @click="cancelPay" class="cancel-btn" type="danger">取消支付</el-button>
          </div>
        </div> -->
        <!-- end:自定义页面内容 -->
         <vUser />
      </div>
    </vCommonPage>
  </div>
</template>
<script>
// 图像
import phoneBgUrl from "@images/payments/phone-bg.jpg"
import QRCode from "qrcode"
import { commonPost } from "@api/data"
import { route, appointent, recipel,inptRechargeReq } from "@js/mixins"
import readingDzjkk from "@images/readcard/reading01.png"
import { countDown } from "@js/mixins"
import {MedInsRegistTrade}from "@js/MIRegist"
import {MedInsBillConformTrade}from "@js/MIBillConform"
export default {
  mixins: [route, appointent, recipel, inptRechargeReq, countDown,MedInsRegistTrade,MedInsBillConformTrade],
  data() {
    return {
     barCode: '',
      timer: null,
      readingUrl:readingDzjkk,
      showWaitingModal: true,
      status: "",
      amount:"",
      phoneBgUrl: phoneBgUrl, // 手机背景图
      qrcodeType: this.$route.query.from, // 支付宝还是微信的二维码
      outTradeNo: "",
      accountType:"",
      payinfo:{
        barCode:"",
        status: "",
        amount:"",
        outPayTradno:"",
        rcptNo:"",
        transNo:"",
        payWay:"",
      }
    };
  },
  methods: {
       handleClose() {
        this.$confirm('确认取消支付?')
          .then(_ => {
          // this.backToPreSatgeEnd();
          this.backToPaycenter()
          })
          .catch(_ => {
            this.$nextTick(function() {
            this.$refs.autofocus.focus()
        });
          });
      },
    nextStep() {
      const preStageName = this.$store.state.route.preStageEnd;
       var isYbPay=this.$store.state.user.isYbPay
       let orginfo = this.$store.state.terminfo.orginfo;
      switch (preStageName) {
          case "mzgh":
            if(isYbPay&&orginfo.cmiid!='104'){//不是延吉医保挂号
              this.CMIRegConfirm();
            }
            else{
              this.sendRegConfirm();
            }
          break;
        case "mzyy":
            if(isYbPay&&orginfo.cmiid!='104'){//不是延吉医保预约取号
              this.CMIRegConfirm();
            }
            else{
              this.sendAppointent();
            }
          break;
        case "mzjs":
            if(isYbPay){
              this.CMIBillConfirm();
            }
            else{
               this.sendRecipel();
            }
          break;
           case "zycz":
          this.sendInptRechargeReq();
          break;
      }
      setTimeout(()=>{
        this.$notify.closeAll();
      },10000)
    },

    cancelPay() {
      // this.backToPreSatgeEnd();
      this.backToPaycenter()
    },
    waitingReadcard() {
       this.amount=this.$store.state.user.userpay
       const preStageName = this.$store.state.route.preStageEnd;
       if(preStageName==='zycz'){
          this.accountType=2;//住院账户类型2
       }
       else{
          this.accountType=1;//门诊账户类型1
       }
       
        this.showWaitingModal = true;
        this.$nextTick(function() {
        this.$refs.autofocus.focus()
      });
      },
    query() {
      let data = {};
      data.url = "/api/barCodePay";
      data.payload = {
        patientId: this.$store.state.user.userinfo.patientId,
        name: this.$store.state.user.userinfo.name,
        accountType:this.accountType,
        amount: this.amount,
        decription: "",
        barCode: this.barCode,
        payWay:this.qrcodeType,
        termId: this.$store.state.terminfo.terminfo.termId,
      };
      commonPost(data).then(res => {
        // let url = res.data.qrcode;
        this.payinfo.outPayTradno = res.data.outPayTradno;
        this.payinfo.transNo = res.data.transNo;
        this.payinfo.rcptNo= res.data.rcptNo;
        this.payinfo.status= res.data.payStatus;
        this.payinfo.payWay=this.qrcodeType;
        this.payinfo.amount=this.amount;
        this.payinfo.barCode=this.barCode;
        this.status =res.data.payStatus;

        // this.dealStatus();
        // this.createQrcode(url);
      }).catch(e=>{
        console.log("支付失败了"+e);
          var isYbPay=this.$store.state.user.isYbPay
          if(isYbPay){
            console.log("支付失败，医保回退"+e);
            this.retYb(e);
          }
         });
    },
   async retYb(e){//回退医保
          this.$notify({
          title: '支付失败',
           type:'error',
          duration:8000,
          message: e.message});
      const preStageName = this.$store.state.route.preStageEnd;
      if(preStageName=='mzgh'||preStageName=='mzyy'){
        this.YB.Trade(1, this.$store.state.medicalInsurance.regmsghis.medInsRetRegistMsg);
      }
      else if(preStageName=='mzjs'){
      //结算撤销
         await this.YB.Trade(1,  this.$store.state.medicalInsurance.confirmhis.medInsRetBillConfirmMsg);
          //费用撤销
         await this.YB.Trade(1, this.$store.state.medicalInsurance.upfeehis.medInsRetUpFeeMsg);
      }
         this.$router.push({ name: "home" });
    },
    checkinfo(){
       this.showWaitingModal = false;
      var patientId=this.$store.state.user.userinfo.patientId;
      console.log("支付patientId="+patientId);
      if(patientId==null||patientId==undefined||patientId=="undefined"){
       this.$alert("抱歉，数据异常，请重新操作", "提示：", {
          confirmButtonText: "确定",
          callback: action => {
            if (action == "confirm" || action == "cancel") {
              this.$store.dispatch("user/updateuserinfo", this.userinfo);
              this.$router.push({ name: "home" });
            }
          }
        });
      }
      else{
         this.query();
      }
    },
    backToPaycenter(){
      const previous = this.$store.state.route.preStageEnd
      this.$router.push({ name: "payments",  query:{from: previous}});
    }
  },
  computed: {
    // 计算属性
    statusData() {
      return this.status;
    }
  },
  watch: {
    statusData: function(status) {
      // 当返回的新值为创建中的时候,保持3秒轮询
      if (status == "pending") {
        this.timer = setInterval(() => {
          setTimeout(this.dealStatus, 0);
        }, 3000);
      }
      // 当返回的新值为成功的时候,关闭定时器,结束轮询
      if (status == "success") {
        this.$store.dispatch("timer/updateShowConfirm", false); // 取消超时确认弹框
        this.$message({
          message: "支付成功！",
          type: "success"
        });
        clearInterval(this.timer);
        this.$store.dispatch("payrecord/updatepayinfo", this.payinfo);
        this.nextStep();
      }
    }
  },
  components: {},
  mounted() {
    // this.$store.dispatch("timer/updateShowConfirm", true); // 设置需要超时确认弹框
    this.waitingReadcard();
    // this.query();
  },
  beforeDestroy: function() {
    clearInterval(this.timer);
  }
};
</script>
<style scoped>
.page-wrap {
  position: absolute;
  top: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.item-wrap {
  position: absolute;
  text-align: center;
}
.phone-bg {
  width: 500px;
  padding: 0 150px;
  box-sizing: border-box;
  height: 500px;
  border-radius: 250px;
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.pay-info {
  position: absolute;
  box-sizing: border-box;
  top: 250px;
  width: 200px;
  padding: 0 20px;
  line-height: 24px;
  font-size: 16px;
  color: #666;
  text-align: left;
}
.qrcode {
  position: relative;
  top: 100px;
}
.cancel-btn {
  margin: 30px 0 0 0;
  font-size: 18px;
  padding: 20px 30px;
}
</style>